package com.example.myapplication.ui.budget;

import android.content.Context;
import android.os.Bundle;
import android.text.format.Time;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.myapplication.App;
import com.example.myapplication.R;
import com.example.myapplication.entity.BorrowAndLoan;
import com.example.myapplication.entity.Budget;
import com.example.myapplication.entity.Pay;
import com.example.myapplication.greendao.BorrowAndLoanDao;
import com.example.myapplication.greendao.BudgetDao;
import com.example.myapplication.greendao.DaoSession;
import com.example.myapplication.greendao.PayDao;
import com.example.myapplication.ui.budget.BottomDialogFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class BudgetFragment extends Fragment {
    private View view = null;
    private Button selecYear;
    private Button bt_budget_confirm;
    private EditText life;
    private EditText travel;
    private EditText food;
    private EditText fun;
    private EditText learn;
    private EditText close;
    private final int H = ViewGroup.LayoutParams.WRAP_CONTENT;
    private final int W = ViewGroup.LayoutParams.MATCH_PARENT;
    private TableLayout tab;
    private ArrayList<String> title = new ArrayList<>();
    private Boolean tab_init = false;
    private App app;
    private DaoSession daoSession;
    private int currentYear;
    private int currentMonth;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_budget, null);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Time t=new Time();
        t.setToNow();
        currentYear = t.year;
        currentMonth = t.month+1;
        life = getActivity().findViewById(R.id.et_life);
        travel = getActivity().findViewById(R.id.et_travel);
        food = getActivity().findViewById(R.id.et_food);
        fun = getActivity().findViewById(R.id.et_fun);
        learn = getActivity().findViewById(R.id.et_learn);
        close = getActivity().findViewById(R.id.et_close);
        selecYear = getActivity().findViewById(R.id.select_year_budget);
        selecYear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BottomDialogFragment f = new BottomDialogFragment();
                f.show(getChildFragmentManager(),"select_year");
            }
        });

        bt_budget_confirm = getActivity().findViewById(R.id.bt_budget_confirm);
        bt_budget_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //构建数据
                Budget budget = new Budget();
                budget.setLife(Double.parseDouble(life.getText().toString()));
                budget.setFood(Double.parseDouble(food.getText().toString()));
                budget.setClose(Double.parseDouble(close.getText().toString()));
                budget.setFun(Double.parseDouble(fun.getText().toString()));
                budget.setLearn(Double.parseDouble(learn.getText().toString()));
                budget.setTravel(Double.parseDouble(travel.getText().toString()));
                budget.setBudgetDate(new Date(currentYear-1900,currentMonth,1));

                //从数据库读取数据
                app = (App) getActivity().getApplication();
                daoSession = app.getDaoSession();
                BudgetDao dao = daoSession.getBudgetDao();
                List<Budget> daoList = dao.loadAll();

                boolean is_empty = true;
                long id = 1;
                if (daoList.isEmpty()){
                    //数据表为空,插入
                    dao.insert(budget);
                }else {
                    for (Budget dao1:daoList){
                        System.out.println(dao1.toString());
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(dao1.getBudgetDate());

                        if (calendar.get(Calendar.YEAR)==currentYear && calendar.get(Calendar.MONTH)==currentMonth){
                            is_empty = false;
                            id = dao1.getId();
                        }
                    }
                    if (is_empty){
                        //没有此条记录，插入一个新的
                        dao.insert(budget);
                    }else {
                        //有记录，更新
                        budget.setId(id);
                        dao.update(budget);
                    }
                }
                Toast.makeText(getActivity().getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
            }
        });
        initData();
        title.add("生活日用");
        title.add("交通出行");
        title.add("餐饮美食");
        title.add("休闲娱乐");
        title.add("文体教育");
        title.add("服饰美容");
        title.add("合计");
        initTab(currentYear,currentMonth);
    }

    public void initData(){
        //初始化显示
        selecYear.setText(currentYear+"年"+currentMonth+"月");
        app = (App) getActivity().getApplication();
        daoSession = app.getDaoSession();
        BudgetDao dao = daoSession.getBudgetDao();
        List<Budget> daoList = dao.loadAll();
        boolean has = false;
        for (Budget dao1:daoList){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dao1.getBudgetDate());
            if (calendar.get(Calendar.YEAR)==currentYear && calendar.get(Calendar.MONTH)==currentMonth){
                life.setText(dao1.getLife()+"");
                food.setText(dao1.getFood()+"");
                close.setText(dao1.getClose()+"");
                fun.setText(dao1.getFun()+"");
                learn.setText(dao1.getLearn()+"");
                travel.setText(dao1.getTravel()+"");
                has = true;
            }
        }
        if (!has){
            life.setText(0+"");
            food.setText(0+"");
            close.setText(0+"");
            fun.setText(0+"");
            learn.setText(0+"");
            travel.setText(0+"");
        }
    }

    public void initTab(int year,int month){
        tab = (TableLayout) getActivity().findViewById(R.id.tab_01);
        if (tab_init){
            tab.removeAllViews();
        }

        //从数据库读取数据
        app = (App) getActivity().getApplication();
        daoSession = app.getDaoSession();
        PayDao dao = daoSession.getPayDao();
        List<Pay> daoList = dao.loadAll();
        if (daoList.isEmpty()){
            return;
        }
        double life=0 ,travel=0,food=0,fun=0,learn=0,close = 0,sum = 0;
        for (Pay pay: daoList){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(pay.getPayDate());

            if (calendar.get(Calendar.YEAR)==year && calendar.get(Calendar.MONTH)+1==month){
                if (pay.getPayType().equals("life")){
                    life+=pay.getPay();
                }else if (pay.getPayType().equals("travel")){
                    travel+=pay.getPay();
                }else if (pay.getPayType().equals("food")){
                    food+=pay.getPay();
                }else if (pay.getPayType().equals("fun")){
                    fun+=pay.getPay();
                }else if (pay.getPayType().equals("learn")){
                    learn+=pay.getPay();
                }else if (pay.getPayType().equals("close")){
                    close+=pay.getPay();
                }else {
                    continue;
                }
                sum+=pay.getPay();
            }
        }
        WindowManager wm = (WindowManager) getActivity()
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = 100;
        //第一行表头单独设置 支出类型，包括 life（生活日用）travel(交通出行) food（餐饮美食） fun（休闲娱乐） learn（文体教育） close（服饰美容）
        TableRow tabRow_title = new TableRow(getActivity());
        for (int i=0;i<title.size();i++){
            TextView tv = new TextView(getActivity());
            tv.setText(title.get(i));
            tv.setGravity(Gravity.CENTER);
            tv.setBackgroundResource(R.drawable.tab);
            tv.setWidth(width/7);
            tv.setHeight(height);
            tabRow_title.addView(tv);
        }
        tab.addView(tabRow_title,new TableLayout.LayoutParams(W,H));

        ArrayList<Double> date = new ArrayList<>();
        date.add(life);
        date.add(travel);
        date.add(food);
        date.add(fun);
        date.add(learn);
        date.add(close);
        //填入数据
        TableRow tab_date = new TableRow(getActivity());
        for (int i=0;i<date.size();i++){
            TextView tv = new TextView(getActivity());
            tv.setText(date.get(i)+"");
            tv.setGravity(Gravity.CENTER);
            tv.setBackgroundResource(R.drawable.tab);
            tv.setWidth(width/7);
            tv.setHeight(height);
            tab_date.addView(tv);
        }

        TextView tv = new TextView(getActivity());
        tv.setText(sum+"");
        tv.setGravity(Gravity.CENTER);
        tv.setBackgroundResource(R.drawable.tab);
        tv.setWidth(width/7);
        tv.setHeight(height);
        tab_date.addView(tv);

        tab.addView(tab_date,new TableLayout.LayoutParams(W,H));

        tab_init = true;
    }

    @Subscribe
    public void onEvent(String data) {
        String[] s = data.split("!");
        selecYear.setText(s[0]+"年"+s[1]+"月");
        currentYear = Integer.parseInt(s[0]);
        currentMonth = Integer.parseInt(s[1]);
        initData();
        initTab(currentYear,currentMonth);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}